package com.example.ReactorModel;

import com.example.NioDemoConfig;
import com.example.util.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class EchoServerReactor implements Runnable{

    Selector selector;
    ServerSocketChannel serverSocket;

    public EchoServerReactor() throws IOException {
        selector = Selector.open();
        serverSocket = ServerSocketChannel.open();

        InetSocketAddress address = new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_IP,NioDemoConfig.SOCKET_SERVER_PORT);
        serverSocket.socket().bind(address);
        Logger.info("服务端已经开始监听: "+address);
        //非阻塞
        serverSocket.configureBlocking(false);
        //注册serverSocket的accept新连接接收事件
        SelectionKey sk = serverSocket.register(selector,SelectionKey.OP_ACCEPT);
        sk.attach(new AcceptorHandler());
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                selector.select();
                Set<SelectionKey> selected = selector.selectedKeys();
                Iterator<SelectionKey> it = selected.iterator();
                while(it.hasNext()) {
                    SelectionKey sk = it.next();
                    dispatch(sk);
                }
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    void dispatch(SelectionKey sk){
        Runnable handler = (Runnable) sk.attachment();
        if(handler != null){
            handler.run();
        }
    }

    /**
     * 处理器：处理新连接
     */
    class AcceptorHandler implements Runnable{
        @Override
        public void run() {
            try {
                SocketChannel channel = serverSocket.accept();
                Logger.info("接收到一个连接");
                if(channel != null){
                    new EchoHandler(selector,channel);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new Thread(new EchoServerReactor()).start();
    }
}
